﻿#include "HnrjitCheckBox.h"
#include "HnrjitContainer.h"

CHnrjitCheckBox::CHnrjitCheckBox()
	: CHnrjitButton()
	, m_isChecked(FALSE)
{
	m_nTextAlign |= DT_VCENTER;
}

void CHnrjitCheckBox::SetAttribute(const TiXmlElement* pxElement, HZIP hZipRes /*= NULL*/)
{
	CHnrjitButton::SetAttribute(pxElement, hZipRes);

	const CHAR* pszValue;
	if (pszValue = pxElement->Attribute("Checked"))
	{
		if (strcmp(pszValue, "true") == 0)
		{
			SetChecked(TRUE);
		}
	}
}

CHnrjitControl::ControlStatus CHnrjitCheckBox::GetControlState() const
{
	if (m_isEnabled && m_pContainer->IsEnabled())
	{
		if (m_isChecked)
		{
			return m_isTriggered ? kNormal : kActivated;
		}
		else
		{
			return m_isTriggered ? kActivated : kNormal;
		}
	}
	else
	{
		return kDisabled;
	}
}

BOOL CHnrjitCheckBox::IsChecked() const
{
	return m_isChecked;
}

void CHnrjitCheckBox::SetChecked(BOOL isChecked)
{
	ATLASSERT(m_dwThreadID == GetCurrentThreadId());
	if (m_isChecked != isChecked)
	{
		m_isChecked = isChecked;
		Invalidate(m_rcGeometry);
	}
}

void CHnrjitCheckBox::DrawControl(HDC hdc)
{
	ImageInfo tagInfo;
	CRect rcReference = m_isTriggered ? CRect(m_rcGeometry.left + 1, m_rcGeometry.top + 1,
		m_rcGeometry.right + 1, m_rcGeometry.bottom + 1) : m_rcGeometry;
	rcReference.MoveToXY(GetLocation() + m_pContainer->GetLocation());

	ControlStatus iControlStatus = GetControlState();
	if (m_strTitle.GetLength())
	{
		DrawRect(hdc, rcReference, iControlStatus);

		if (m_spBackIcons[iControlStatus] && m_spBackIcons[iControlStatus]->GetImageInfo(&tagInfo) == S_OK)
		{
			long x, y, w, h;
			w = tagInfo.Width;
			h = tagInfo.Height;
			x = rcReference.left + 3;
			y = (rcReference.top + rcReference.bottom - w) / 2;; // rcReference.top + (rcReference.Height() - tagInfo.Height) / 2;

			CRect rcPicture = CRect(CPoint(x, y), CSize(w, h));
			DrawImage(hdc, rcPicture, iControlStatus);

			// 图片两侧及最右侧留三个像素
			x = rcReference.left + w + 6; // rcReference.left + rcPicture.Width() + 6;
			y = rcReference.top;
			w = rcReference.right - x - 3; // rcReference.Width() - (rcPicture.Width() + 6 - 3);
			h = rcReference.Height();

			CRect rcText = CRect(CPoint(x, y), CSize(w, h));
			DrawTitle(hdc, rcText, iControlStatus);
		}
		else
		{
			DrawTitle(hdc, rcReference, iControlStatus);
		}
	}
	else
	{
		if (m_spBackIcons[iControlStatus])
		{
			DrawImage(hdc, rcReference, iControlStatus);
		}
		else
		{
			DrawRect(hdc, rcReference, iControlStatus);
		}
	}
}

void CHnrjitCheckBox::OnMousePress(UINT nFlags, CPoint point)
{
	ATLASSERT(m_dwThreadID == GetCurrentThreadId());
	if (!m_isTriggered)
	{
		m_isTriggered = TRUE;
		Invalidate(m_rcGeometry);
	}
}

void CHnrjitCheckBox::OnMouseRelease(UINT nFlags, CPoint point)
{
	ATLASSERT(m_dwThreadID == GetCurrentThreadId());
	if (m_isTriggered)
	{
		m_isTriggered = FALSE;
		SetChecked(!m_isChecked);
		OnClicked();
	}
}
